package ex.hql.mail;

import com.rabbitmq.client.Channel;
import ex.hql.pojo.Employee;
import ex.hql.pojo.MailConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * @program:yeb
 * @author: hql
 * @Time: 2021/9/5  11:50
 * @description: 消息接收者
 */
@Component
public class MailReceiver {

    private static  final Logger log= LoggerFactory.getLogger(MailReceiver.class);

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private MailProperties mailProperties;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private RedisTemplate redisTemplate;



    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
    public void handler(Message message, Channel channel) throws MessagingException {
        Employee employee = (Employee) message.getPayload();
        MessageHeaders headers = message.getHeaders();
        //消息序号
        Long tag = ((Long) headers.get(AmqpHeaders.DELIVERY_TAG));
        String msgId = (String) headers.get("spring_returned_message_correlation");
        HashOperations hash = redisTemplate.opsForHash();
        MimeMessage mimeMessage= javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper=new MimeMessageHelper(mimeMessage,true);
        try {
            if(hash.hasKey("mail_log",msgId)){
                log.error("消息已经被消费==============》{}",msgId);
                /**
                 * 手动确认消息
                 */
                channel.basicAck(tag,false);
                System.out.println("if里面的回执判断触发了============》");

            }else{
                System.out.println("发送邮件之前触发=====》");
                //发件人
                messageHelper.setFrom(mailProperties.getUsername());
                //收件人
                messageHelper.setTo(employee.getEmail());
                //主题
                messageHelper.setSubject("入职欢迎邮件");
                //发送日期
                messageHelper.setSentDate(new Date());
                //邮件内容
                Context context=new Context();
                context.setVariable("name",employee.getName());
                context.setVariable("posName",employee.getPosition().getName());
                context.setVariable("jobLevelName",employee.getJoblevel().getName());
                context.setVariable("departmentName",employee.getDepartment().getName());
                String mail = templateEngine.process("mail", context);
                messageHelper.setText(mail,true);
                javaMailSender.send(mimeMessage);
                log.info("邮件发送成功！");
                hash.put("mail_log",msgId,"ok");
                //手动确认消息
                channel.basicAck(tag,false);
                System.out.println("if外面的回执触发了=========》");

            }

        } catch (Exception e) {
            /**
             * tag 消息序号
             * multiple 是否确认多条
             * requeue 将消息退回队列
             */
            try {
                channel.basicNack(tag,false,true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            log.error("邮件发送失败==========》{}",e.getMessage());
        }

    }


}
